package com.csun.dsms.controller;

import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.education.JyProblemManagement;
import com.csun.dsms.model.education.JyProblemManagementRecord;
import com.csun.dsms.model.education.JyQueryDto;
import com.csun.dsms.model.education.JyUser;
import com.csun.dsms.model.huang.*;
import com.csun.dsms.service.*;
import com.csun.dsms.utils.ExportExcel;
import com.csun.dsms.utils.pt.IHuangGangUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 教育整顿
 * @desc   i黄冈数据处理
 */
@Slf4j
@RestController
@RequestMapping("/jyData")
public class JyDataController {

    @Resource
    private JyDataService jyDataService;

    @Resource
    private HuangGangService huangGangService;

    @Resource
    private JyUserService jyUserService;

    @Resource
    private JyReminderDataService jyReminderDataService;

    @Resource
    private JyProblemManagementRecordService jyProblemManagementRecordService;

    @Authorization
    @RequestMapping(value = "/getQrCode",method = RequestMethod.POST)
    public Wrapper getQrCode() {
        String result = IHuangGangUtil.jyLogin();
        return WrapMapper.ok(result);
    }

    /**
     * i黄冈登录 获取用户的UserId 和身份证号
     * @param oToken
     * @return
     */
    @Authorization
    @RequestMapping(value = "/getPhone",method = RequestMethod.POST)
    public Wrapper login(@RequestBody String oToken) {
        System.out.println("++++");
        System.out.println(oToken);
        JSONObject aesJsonBean = JSONObject.parseObject(oToken);
        System.out.println(aesJsonBean);
        String iHgToken = aesJsonBean.getString("oToken");
        System.out.println(iHgToken);
        String phone = huangGangService.getPhone(iHgToken);
        return WrapMapper.ok(phone);
    }

    /**
     * i黄冈登录校验 扫码
     * 用户登录调取比对数据库是否存在（手机号和身份证号码），存在即可登录，返回user表，不存在抛异常
     */
    @Authorization
    @RequestMapping(value = "/loginCheck",method = RequestMethod.POST)
    public Wrapper loginCheck(@RequestBody String uuid) {
        JSONObject aesJsonBean = JSONObject.parseObject(uuid);
        String UID = aesJsonBean.getString("uuid");
        String data = IHuangGangUtil.getCodeResult(UID);
        if (ObjectUtils.isEmpty(data)){
            return WrapMapper.error("禁止登录");
        }else{
            JSONObject jsonObject = JSONObject.parseObject(data);
            if (jsonObject.getIntValue("code") == 1){
                String dataStr = jsonObject.getString("data");
                System.out.println(dataStr);
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                String userType = dataJson.getString("userType");
                System.out.println(userType);
                String userPhone = "";
                if (userType!=null && userType.equals("1")){
                    userPhone = dataJson.getString("mobilePhone");
                }else if (userType!=null && userType.equals("2")){
                    userPhone = dataJson.getString("agentMobile");
                }
                JyUser user = jyUserService.loginByPhone(userPhone);
                if (ObjectUtils.isEmpty(user)){
                    return WrapMapper.error("禁止登录");
                }else{
                    return WrapMapper.ok(user);
                }
            }
            return WrapMapper.error("禁止登录");
        }
    }



    @Authorization
    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    public Wrapper getUserList(@RequestBody JyQueryDto jyQueryDto){
        List userList = jyUserService.queryList(jyQueryDto);
        return WrapMapper.ok(userList);
    }

    @Authorization
    @RequestMapping(value = "/editUser",method = RequestMethod.POST)
    public Wrapper editUser (@RequestBody JyUser hgUser){
        Integer result = jyUserService.update(hgUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
    }

    @Authorization
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public Wrapper addUser (@RequestBody JyUser hgUser){
        Integer result = jyUserService.save(hgUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
    }


    @Authorization
    @PostMapping(value = "/deleteUserById/{id}")
    public Wrapper deleteById (@PathVariable Long id){
        Integer result = jyUserService.deleteByKey(id);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
    }

    /*
     * 查询教育数据
     * */
    @Authorization
    @RequestMapping(value = "/queryData",method = RequestMethod.POST)
    public Wrapper queryData (@RequestBody JyQueryDto jyQueryDto){
        PageInfo page = jyDataService.queryListWithPage(jyQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,page);
    }


    /**
     * 新增政府服务数据
     */
    @Authorization
    @RequestMapping(value = "/addData",method = RequestMethod.POST)
    public Wrapper addData (@RequestBody JyProblemManagement jyProblemManagement){
        int result = jyDataService.save(jyProblemManagement);
        jyReminderDataService.addReminder(jyProblemManagement);
        if (result>0){
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
        }else{
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE,result);
        }
    }

    /**
     * 修改政府服务数据
     */
    @Authorization
    @RequestMapping(value = "/updateData",method = RequestMethod.POST)
    public Wrapper updateData (@RequestBody JyProblemManagement jyProblemManagement){
        int result = jyDataService.update(jyProblemManagement);
        if (result>0){
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
        }else{
            return WrapMapper.wrap(Wrapper.ERROR_CODE,Wrapper.ERROR_MESSAGE,result);
        }
    }

    /**
     * 删除政府服务数据
     */
    @Authorization
    @RequestMapping(value = "/deleteData",method = RequestMethod.POST)
    public Wrapper deleteData (@RequestBody JyProblemManagement jyProblemManagement) {
        int result = jyDataService.deleteByKey(jyProblemManagement.getId());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,result);
    }


    @GetMapping("/downDataTemplate")
    public void downGovernmentDataTemplate(HttpServletResponse response,IHgQueryDto iHgQueryDto) {
        HSSFWorkbook wb = new HSSFWorkbook();
        String worksheetTitle = "学习教育突出问题整治工作台账导入模版表";
        // 创建单元格样式
        HSSFCellStyle cellStyleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        cellStyleTitle.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cellStyleTitle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时不换行
        cellStyleTitle.setWrapText(false);
        // ------------------------------------------------------------------
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 指定单元格居中对齐
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时换行
        cellStyle.setWrapText(true);
        // 创建日期格式样式
        HSSFCellStyle dateCellStyle = wb.createCellStyle();
        dateCellStyle.cloneStyleFrom(cellStyle);
        short dateFormat = wb.createDataFormat().getFormat("yyyy年MM月dd日");
        dateCellStyle.setDataFormat(dateFormat);
        // ------------------------------------------------------------------
        // 设置单元格字体
        HSSFFont font = wb.createFont();
         font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeight((short) 200);
        cellStyleTitle.setFont(font);

        // 工作表名
        String areaName = "区划地名";
        String department = "部门名称";
        String projectName = "服务项目名称";
        String remarkOne = "所有渠道办理的总办件数";
        String remarkTwo = "所有渠道办理涉及的总金额（万元）";
        String remarkThree = "i黄冈办理的办件数";
        String remarkFour = "i黄冈办理涉及的金额（万元）";
        String creator = "填报人";
        String createdTime = "填报时间";

        HSSFSheet sheet = wb.createSheet();
        ExportExcel exportExcel = new ExportExcel(wb, sheet);
        // 创建报表头部
        //exportExcel.createNormalHead(worksheetTitle, 11);
        // 定义第一行
        HSSFRow row1 = sheet.createRow(0);
        //第一行第1列
        HSSFCell cell1 = row1.createCell(0);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(areaName));
        sheet.setColumnWidth(0, 20 * 256);;
        //第一行第2列
        cell1 = row1.createCell(1);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(department));
        sheet.setColumnWidth(1, 20 * 256);
        //第一行第3列
        cell1 = row1.createCell(2);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(projectName));
        sheet.setColumnWidth(2, 20 * 256);

        //第一行第5列
        cell1 = row1.createCell(3);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(remarkOne));
        sheet.setColumnWidth(3, 20 * 256);
        //第一行第6列
        cell1 = row1.createCell(4);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(remarkTwo));
        sheet.setColumnWidth(4, 20 * 256);
        //第一行第7列
        cell1 = row1.createCell(5);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(remarkThree));
        sheet.setColumnWidth(5, 20 * 256);
        //第一行第7列
        cell1 = row1.createCell(6);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(remarkFour));
        sheet.setColumnWidth(6, 20 * 256);
        //第一行第7列
        cell1 = row1.createCell(7);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(creator));
        sheet.setColumnWidth(7, 20 * 256);
        //第一行第7列
        //第一行第7列
        cell1 = row1.createCell(8);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(createdTime));
        sheet.setColumnWidth(8, 20 * 256);
        for (int i = 1; i <= 500; i++) {
            HSSFRow dataRow = sheet.createRow(i);
            if (!StringUtils.isEmpty(iHgQueryDto.getDepartment())){
                if (i<3){
                    dataRow.createCell(1).setCellValue(iHgQueryDto.getDepartment());
                    dataRow.createCell(2).setCellValue(iHgQueryDto.getProjectName());
                }
            }
            HSSFCell dateCell = dataRow.createCell(8);
            dateCell.setCellStyle(dateCellStyle);

        }

        String fileName = worksheetTitle;
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xls");// 指定下载的文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            OutputStream output = response.getOutputStream();
            wb.write(output);
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//    /**
//     * 导入政府服务数据
//     */
//    @Authorization
//    @RequestMapping(value = "/importGovernmentData",method = RequestMethod.POST)
//    public Wrapper importGovernmentData (@RequestParam("file") MultipartFile file,@RequestParam("userName") String userName) {
//        return ihgDataProcessService.importGovernmentData(file,userName);
//    }

    //queryGovernmentStatistical
    @GetMapping("/downExcelData")
    public void downExcelDataGet(HttpServletResponse response) {
        jyDataService.downExcelData(response);
    }

    //导出表格模板数据
    @RequestMapping(value = "/downExcelData",method = RequestMethod.POST)
    public void downExcelData (HttpServletResponse response) {
        jyDataService.downExcelData(response);
    }

    //导入数据
    @RequestMapping(value = "/importData",method = RequestMethod.POST)
    public Wrapper<Object> importData (@RequestParam("file") MultipartFile file) {
        return jyDataService.importData(file);
    }

    //查询提醒数据
    @RequestMapping(value = "/queryReminderData",method = RequestMethod.POST)
    public Wrapper<Object> queryReminderData (@RequestBody JSONObject reqJson) {
        return jyReminderDataService.queryReminderData(reqJson);
    }

    //设置提醒已读
    @RequestMapping(value = "/setReminderRead",method = RequestMethod.POST)
    public Wrapper<Object> setReminderRead (@RequestBody JSONObject reqJson) {
        return jyReminderDataService.setReminderRead(reqJson);
    }

    //查询问题管理数据
    @RequestMapping(value = "/queryProblemManagementPage",method = RequestMethod.POST)
    public Wrapper<PageInfo<JyProblemManagement>> queryProblemManagementPage (@RequestBody JSONObject reqJson) {
        return jyDataService.queryProblemManagementPage(reqJson);
    }


    @RequestMapping(value = "/queryProblemManagementPageTotal",method = RequestMethod.POST)
    public Wrapper<JyProblemManagement> queryProblemManagementPageTotal (@RequestBody JSONObject reqJson) {
        return jyDataService.queryProblemManagementTotal(reqJson);
    }


    //查询问题管理记录
    @RequestMapping(value = "/addManagementRecord",method = RequestMethod.POST)
    public Wrapper<Object> addManagementRecord (@RequestBody JyProblemManagementRecord jyProblemManagementRecord) {
        return jyProblemManagementRecordService.addManagementRecord(jyProblemManagementRecord);
    }

    //查询管理记录统计
    @RequestMapping(value = "/queryManagementRecordStatistics",method = RequestMethod.POST)
    public Wrapper<Object> queryManagementRecordStatistics (@RequestBody JSONObject reqJson) {
        return jyProblemManagementRecordService.queryManagementRecordStatistics(reqJson);
    }

    //导出问题管理
    @RequestMapping(value = "/exportAllData",method = RequestMethod.POST)
    public void exportAllData (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        jyDataService.exportAllData(response,reqJson);
    }

    //导出问题管理（部门）
    @RequestMapping(value = "/dataByDepartment",method = RequestMethod.POST)
    public Wrapper<Object> dataByDepartment (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByDepartment(response,reqJson);
    }

    //导出问题管理（区划）
    @RequestMapping(value = "/dataByArea",method = RequestMethod.POST)
    public Wrapper<Object> dataByArea (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByArea(response,reqJson);
    }

    //导出问题管理（五大问题）
    @RequestMapping(value = "/dataByBigTypeName",method = RequestMethod.POST)
    public Wrapper<Object> dataByBigTypeName (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByBigTypeName(response,reqJson);
    }

    //导出问题管理（清单查摆问题表现）
    @RequestMapping(value = "/dataByProminentProblem",method = RequestMethod.POST)
    public Wrapper<Object> dataByProminentProblem (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByProminentProblem(response,reqJson);
    }

    //导出问题管理（突出问题类型数据统计）
    @RequestMapping(value = "/dataByProblemType",method = RequestMethod.POST)
    public Wrapper<Object> dataByProblemType (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByProblemType(response,reqJson);
    }

    //导出问题管理（建章立制情况一览表）
    @RequestMapping(value = "/exportDataByEstablished",method = RequestMethod.POST)
    public void exportDataByEstablished (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        jyDataService.exportDataByEstablished(response,reqJson);
    }

    //导出问题管理（十大攻坚问题类型）
    @RequestMapping(value = "/dataByIsTopTen",method = RequestMethod.POST)
    public Wrapper<Object> dataByIsTopTen (HttpServletResponse response, @RequestBody JSONObject reqJson) {
        return jyDataService.dataByIsTopTen(response,reqJson);
    }


}
